//
//  SPGameScene.m
//  shandong_porker
//
//  Created by Developer on 2025-01-08.
//  Copyright © 2025 ShandongPoker. All rights reserved.
//

#import "SPGameScene.h"
#import "../../Core/Categories/UIColor+Theme.h"
#import "../../Models/Game/SPCard.h"
#import "../../Models/Game/SPPlayer.h"
#import "../../ViewModels/Game/SPGameViewModel.h"
#import "../../Models/Game/SPHandEvaluator.h"

@interface SPGameScene ()

@property (nonatomic, strong, readwrite) SKShapeNode *pokerTable;
@property (nonatomic, strong, readwrite) SKNode *communityCardsNode;
@property (nonatomic, strong, readwrite) SKLabelNode *potLabel;
@property (nonatomic, strong, readwrite) SKLabelNode *gameStateLabel;
@property (nonatomic, strong, readwrite) SKNode *actionButtonsNode;

@end

@implementation SPGameScene

#pragma mark - 初始化方法

- (instancetype)initWithSize:(CGSize)size gameManager:(SPGameManager *)gameManager {
    self = [super initWithSize:size];
    if (self) {
        _gameManager = gameManager;
        _gameManager.delegate = self;
        [self setupScene];
    }
    return self;
}

#pragma mark - Setup Methods

- (void)setupScene {
    [super setupScene];
    
    // 设置背景色
    self.backgroundColor = [UIColor sp_backgroundDarkColor];
    
    // 创建扑克桌
    [self createPokerTable];
    
    // 创建UI元素
    [self createUIElements];
    
    // 创建玩家位置
    [self createPlayerPositions];
    
    // 创建操作按钮
    [self createActionButtons];
}

- (void)bindViewModel {
    [super bindViewModel];
    // 暂时为空，避免ViewModel相关的错误
}

#pragma mark - Node Creation

- (void)createPokerTable {
    // 创建全局绿色背景（竖屏布局）
    self.pokerTable = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(self.size.width, self.size.height)];
    self.pokerTable.position = CGPointMake(self.size.width / 2, self.size.height / 2);
    self.pokerTable.fillColor = [UIColor sp_pokerGreenColor];
    self.pokerTable.strokeColor = [UIColor clearColor];
    self.pokerTable.lineWidth = 0;
    self.pokerTable.name = @"pokerTable";
    self.pokerTable.zPosition = 0; // 设置为最底层背景
    
    [self addChild:self.pokerTable];
}

- (void)createUIElements {
    // 顶部状态栏
    [self createTopStatusBar];
    
    // 公共牌区域
    [self createCommunityCardsArea];
    
    // 底部玩家区域
    [self createPlayerActionArea];
}

- (void)createTopStatusBar {
    // 考虑灵动岛的高度，调整顶部位置
    CGFloat topMargin = 140; // 增加顶部边距，避免与按钮重叠
    
    // 移除旧的标签节点（如果存在）
    if (self.potLabel) {
        [self.potLabel removeFromParent];
    }
    if (self.gameStateLabel) {
        [self.gameStateLabel removeFromParent];
    }
    if (self.roundLabel) {
        [self.roundLabel removeFromParent];
    }
    
    // 底池标签 - 放在左侧
    self.potLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    self.potLabel.text = @"底池: ¥0";
    self.potLabel.fontSize = 16; // 减小字体大小
    self.potLabel.fontColor = [UIColor sp_chipGoldColor];
    self.potLabel.position = CGPointMake(80, self.size.height - topMargin); // 左侧位置
    self.potLabel.zPosition = 10;
    [self addChild:self.potLabel];
    
    // 轮次标签 - 放在中间
    self.roundLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    self.roundLabel.text = @"第1轮";
    self.roundLabel.fontSize = 16; // 减小字体大小
    self.roundLabel.fontColor = [UIColor sp_primaryTextColor];
    self.roundLabel.position = CGPointMake(self.size.width / 2, self.size.height - topMargin); // 中间位置
    self.roundLabel.zPosition = 10;
    [self addChild:self.roundLabel];
    
    // 游戏状态标签 - 放在右侧
    self.gameStateLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial"];
    self.gameStateLabel.text = @"等待开始";
    self.gameStateLabel.fontSize = 14; // 减小字体大小
    self.gameStateLabel.fontColor = [UIColor sp_primaryTextColor];
    self.gameStateLabel.position = CGPointMake(self.size.width - 80, self.size.height - topMargin); // 右侧位置
    self.gameStateLabel.zPosition = 10;
    [self addChild:self.gameStateLabel];
    
    // 添加分隔线
    [self createSeparatorLines];
}

- (void)createSeparatorLines {
    // 第一条分隔线 - 顶部区域
    SKShapeNode *line1 = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(self.size.width - 40, 1)];
    line1.position = CGPointMake(self.size.width / 2, self.size.height - 140);
    line1.fillColor = [UIColor sp_chipGoldColor];
    line1.strokeColor = [UIColor sp_chipGoldColor];
    line1.zPosition = 5;
    [self addChild:line1];
    
    // 第三条分隔线 - 底部区域
    SKShapeNode *line3 = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(self.size.width - 40, 1)];
    line3.position = CGPointMake(self.size.width / 2, 220);
    line3.fillColor = [UIColor sp_chipGoldColor];
    line3.strokeColor = [UIColor sp_chipGoldColor];
    line3.zPosition = 5;
    [self addChild:line3];
}

- (void)createCommunityCardsArea {
    // 创建公共牌区域 - 往下移动一些
    self.communityCardsNode = [SKNode node];
    self.communityCardsNode.position = CGPointMake(self.size.width / 2, self.size.height / 2 + 20); // 往下移动一些，从+50改为+20
    self.communityCardsNode.zPosition = 5;
    [self addChild:self.communityCardsNode];
    
    // 公共牌区域背景 - 优化设计
    SKShapeNode *communityArea = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(320, 100) cornerRadius:12];
    communityArea.fillColor = [UIColor colorWithWhite:0.0 alpha:0.4];
    communityArea.strokeColor = [UIColor sp_chipGoldColor];
    communityArea.lineWidth = 3;
    communityArea.position = CGPointMake(0, 0);
    communityArea.zPosition = 5;
    [self.communityCardsNode addChild:communityArea];
    
    // 公共牌标签 - 优化位置
    SKLabelNode *communityLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    communityLabel.text = @"公共牌区域";
    communityLabel.fontSize = 16;
    communityLabel.fontColor = [UIColor sp_secondaryTextColor];
    communityLabel.position = CGPointMake(0, 60);
    communityLabel.zPosition = 6;
    [self.communityCardsNode addChild:communityLabel];
}

- (void)createPlayerActionArea {
    // 玩家手牌区域 - 优化设计
    SKShapeNode *playerCardsArea = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(220, 90) cornerRadius:10]; // 减小尺寸
    playerCardsArea.position = CGPointMake(self.size.width / 2, 160);
    playerCardsArea.fillColor = [UIColor colorWithWhite:0.0 alpha:0.4];
    playerCardsArea.strokeColor = [UIColor sp_chipGoldColor];
    playerCardsArea.lineWidth = 3;
    playerCardsArea.zPosition = 5;
    [self addChild:playerCardsArea];
    
    // 筹码显示 - 调整位置避免被边框裁剪
    SKLabelNode *chipsLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    chipsLabel.text = @"筹码: ¥1000";
    chipsLabel.fontSize = 14; // 减小字体大小
    chipsLabel.fontColor = [UIColor sp_chipGoldColor];
    chipsLabel.position = CGPointMake(self.size.width / 2, 135); // 调整位置，避免被玩家手牌区域边框裁剪
    chipsLabel.zPosition = 6;
    [self addChild:chipsLabel];
    
    // 操作按钮区域
    [self createActionButtons];
}

- (void)createPlayerPositions {
    // 创建玩家位置节点数组
    self.playerNodes = [NSMutableArray array];
    
    // 4个AI玩家位置，分布在扑克桌周围（竖屏布局）- 调整位置确保所有玩家可见
    NSInteger playerCount = 4;
    CGFloat centerX = self.size.width / 2;
    CGFloat centerY = self.size.height / 2;
    
    // 定义4个玩家位置：左上、右上、左下、右下 - 调整位置避免重叠
    CGPoint positions[] = {
        CGPointMake(centerX - 120, centerY + 120),   // 左上 AI-1 - 往上移动
        CGPointMake(centerX + 120, centerY + 120),   // 右上 AI-2 - 往上移动
        CGPointMake(centerX - 120, centerY - 80),    // 左下 AI-3 - 往上移动，避免与底部区域重叠
        CGPointMake(centerX + 120, centerY - 80)     // 右下 AI-4 - 往上移动，避免与底部区域重叠
    };
    
    for (NSInteger i = 0; i < playerCount; i++) {
        SKNode *playerNode = [self createAINodeAtPosition:positions[i] playerIndex:i];
        [self.playerNodes addObject:playerNode];
        [self addChild:playerNode];
    }
}

- (SKNode *)createAINodeAtPosition:(CGPoint)position playerIndex:(NSInteger)index {
    SKNode *playerNode = [SKNode node];
    playerNode.position = position;
    playerNode.name = [NSString stringWithFormat:@"ai_player_%ld", (long)index];
    
    // AI玩家背景 - 减小尺寸避免超出屏幕
    SKShapeNode *background = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(120, 80) cornerRadius:8];
    background.fillColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    background.strokeColor = [UIColor sp_chipGoldColor];
    background.lineWidth = 2;
    background.zPosition = 2;
    [playerNode addChild:background];
    
    // AI玩家名称标签 - 统一字体为Arial-BoldMT
    SKLabelNode *nameLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    nameLabel.text = [NSString stringWithFormat:@"AI-%ld", (long)index + 1];
    nameLabel.fontSize = 12; // 减小字体大小
    nameLabel.fontColor = [UIColor sp_primaryTextColor];
    nameLabel.position = CGPointMake(0, 28); // 调整位置，避免被顶部边框裁剪
    nameLabel.zPosition = 3;
    [playerNode addChild:nameLabel];
    
    // 筹码标签 - 统一字体为Arial-BoldMT
    SKLabelNode *chipsLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    chipsLabel.text = @"¥1000";
    chipsLabel.fontSize = 10; // 减小字体大小
    chipsLabel.fontColor = [UIColor sp_chipGoldColor];
    chipsLabel.position = CGPointMake(0, 10); // 调整位置，避免被边框裁剪
    chipsLabel.zPosition = 3;
    [playerNode addChild:chipsLabel];
    
    // 状态标签 - 统一字体为Arial-BoldMT
    SKLabelNode *statusLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    statusLabel.text = @"等待中";
    statusLabel.fontSize = 8; // 减小字体大小
    statusLabel.fontColor = [UIColor sp_secondaryTextColor];
    statusLabel.position = CGPointMake(0, -5); // 调整位置，避免被底部边框裁剪
    statusLabel.zPosition = 3;
    [playerNode addChild:statusLabel];
    
    return playerNode;
}

- (void)createActionButtons {
    // 创建操作按钮区域
    self.actionButtonsNode = [SKNode node];
    self.actionButtonsNode.position = CGPointMake(self.size.width / 2, 80);
    self.actionButtonsNode.zPosition = 10;
    [self addChild:self.actionButtonsNode];
    
    // 开始游戏按钮 - 新增
    SKShapeNode *startButton = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(120, 40) cornerRadius:6];
    startButton.position = CGPointMake(0, 60); // 放在最上面
    startButton.fillColor = [UIColor colorWithRed:0.2 green:0.6 blue:0.2 alpha:0.9];
    startButton.strokeColor = [UIColor colorWithRed:0.1 green:0.4 blue:0.1 alpha:1.0];
    startButton.lineWidth = 2;
    startButton.name = @"startButton";
    startButton.zPosition = 8;
    [self.actionButtonsNode addChild:startButton];
    
    SKLabelNode *startLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    startLabel.text = @"开始游戏";
    startLabel.fontSize = 14;
    startLabel.fontColor = [UIColor whiteColor];
    startLabel.position = CGPointMake(0, 0);
    startLabel.zPosition = 9;
    [startButton addChild:startLabel];
    
    // 弃牌按钮 - 优化设计
    SKShapeNode *foldButton = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(80, 40) cornerRadius:6]; // 减小尺寸
    foldButton.position = CGPointMake(-120, 0); // 减小间距
    foldButton.fillColor = [UIColor colorWithRed:0.8 green:0.2 blue:0.2 alpha:0.9];
    foldButton.strokeColor = [UIColor colorWithRed:0.6 green:0.1 blue:0.1 alpha:1.0];
    foldButton.lineWidth = 2;
    foldButton.name = @"foldButton";
    foldButton.zPosition = 8;
    [self.actionButtonsNode addChild:foldButton];
    
    SKLabelNode *foldLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    foldLabel.text = @"弃牌";
    foldLabel.fontSize = 14; // 减小字体大小
    foldLabel.fontColor = [UIColor whiteColor];
    foldLabel.position = CGPointMake(0, 0);
    foldLabel.zPosition = 9;
    [foldButton addChild:foldLabel];
    
    // 跟注按钮 - 优化设计
    SKShapeNode *callButton = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(100, 40) cornerRadius:6]; // 减小尺寸
    callButton.position = CGPointMake(0, 0);
    callButton.fillColor = [UIColor colorWithRed:0.2 green:0.6 blue:0.2 alpha:0.9];
    callButton.strokeColor = [UIColor colorWithRed:0.1 green:0.4 blue:0.1 alpha:1.0];
    callButton.lineWidth = 2;
    callButton.name = @"callButton";
    callButton.zPosition = 8;
    [self.actionButtonsNode addChild:callButton];
    
    SKLabelNode *callLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    callLabel.text = @"跟注 ¥200";
    callLabel.fontSize = 14; // 减小字体大小
    callLabel.fontColor = [UIColor whiteColor];
    callLabel.position = CGPointMake(0, 0);
    callLabel.zPosition = 9;
    [callButton addChild:callLabel];
    
    // 加注按钮 - 优化设计
    SKShapeNode *raiseButton = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(80, 40) cornerRadius:6]; // 减小尺寸
    raiseButton.position = CGPointMake(120, 0); // 减小间距
    raiseButton.fillColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.8 alpha:0.9];
    raiseButton.strokeColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.6 alpha:1.0];
    raiseButton.lineWidth = 2;
    raiseButton.name = @"raiseButton";
    raiseButton.zPosition = 8;
    [self.actionButtonsNode addChild:raiseButton];
    
    SKLabelNode *raiseLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    raiseLabel.text = @"加注";
    raiseLabel.fontSize = 14; // 减小字体大小
    raiseLabel.fontColor = [UIColor whiteColor];
    raiseLabel.position = CGPointMake(0, 0);
    raiseLabel.zPosition = 9;
    [raiseButton addChild:raiseLabel];
}

#pragma mark - 游戏控制方法

- (void)startNewGame {
    NSLog(@"GameScene: 开始新游戏");
    [self updateGameStateDisplay:SPGameStateIdle];
    [self updatePotDisplay:0];
}

#pragma mark - 动画方法

- (void)dealCards:(NSArray<SPCard *> *)cards 
       toPosition:(CGPoint)toPosition 
       completion:(void(^)(void))completion {
    NSLog(@"GameScene: 发牌动画到位置 %@", NSStringFromCGPoint(toPosition));
    
    // 简单的发牌动画
    for (NSInteger i = 0; i < cards.count; i++) {
        SPCard *card = cards[i];
        
        // 创建牌面显示
        SKLabelNode *cardNode = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
        cardNode.text = [card description];
        cardNode.fontSize = 14;
        cardNode.fontColor = [UIColor whiteColor];
        cardNode.position = CGPointMake(-50 + i * 30, 0);
        cardNode.zPosition = 1;
        
        // 添加到目标位置
        SKNode *targetNode = [SKNode node];
        targetNode.position = toPosition;
        [self addChild:targetNode];
        [targetNode addChild:cardNode];
        
        // 简单的移动动画
        SKAction *moveAction = [SKAction moveTo:CGPointMake(0, 0) duration:0.5];
        [cardNode runAction:moveAction completion:^{
            if (i == cards.count - 1 && completion) {
                completion();
            }
        }];
    }
}

- (void)moveChips:(NSInteger)amount 
     fromPosition:(CGPoint)fromPosition 
       toPosition:(CGPoint)toPosition 
       completion:(void(^)(void))completion {
    NSLog(@"GameScene: 筹码移动动画 %ld 从 %@ 到 %@", (long)amount, NSStringFromCGPoint(fromPosition), NSStringFromCGPoint(toPosition));
    
    // 创建筹码显示
    SKLabelNode *chipNode = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    chipNode.text = [NSString stringWithFormat:@"¥%ld", (long)amount];
    chipNode.fontSize = 16;
    chipNode.fontColor = [UIColor sp_chipGoldColor];
    chipNode.position = fromPosition;
    chipNode.zPosition = 8;
    [self addChild:chipNode];
    
    // 移动动画
    SKAction *moveAction = [SKAction moveTo:toPosition duration:0.8];
    [chipNode runAction:moveAction completion:^{
        [chipNode removeFromParent];
        if (completion) {
            completion();
        }
    }];
}

- (void)showWinnerAnimation:(CGPoint)winnerPosition winAmount:(NSInteger)winAmount {
    NSLog(@"GameScene: 显示胜利动画在位置 %@，获胜金额 %ld", NSStringFromCGPoint(winnerPosition), (long)winAmount);
    
    // 创建胜利标签
    SKLabelNode *winnerLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    winnerLabel.text = [NSString stringWithFormat:@"获胜! ¥%ld", (long)winAmount];
    winnerLabel.fontSize = 24;
    winnerLabel.fontColor = [UIColor sp_chipGoldColor];
    winnerLabel.position = winnerPosition;
    winnerLabel.zPosition = 15;
    [self addChild:winnerLabel];
    
    // 闪烁动画
    SKAction *fadeOut = [SKAction fadeAlphaTo:0.3 duration:0.5];
    SKAction *fadeIn = [SKAction fadeAlphaTo:1.0 duration:0.5];
    SKAction *blink = [SKAction sequence:@[fadeOut, fadeIn]];
    SKAction *repeat = [SKAction repeatAction:blink count:3];
    
    [winnerLabel runAction:repeat completion:^{
        [winnerLabel removeFromParent];
    }];
}

- (void)updateCommunityCards:(NSArray<SPCard *> *)cards round:(SPGameState)round {
    NSLog(@"GameScene: 更新公共牌，轮次 %ld", (long)round);
    
    // 根据游戏状态确定轮次
    NSInteger roundNumber = 1;
    switch (round) {
        case SPGameStatePreFlop:
            roundNumber = 1;
            break;
        case SPGameStateFlop:
            roundNumber = 2;
            break;
        case SPGameStateTurn:
            roundNumber = 3;
            break;
        case SPGameStateRiver:
            roundNumber = 4;
            break;
        case SPGameStateShowdown:
            roundNumber = 5;
            break;
        default:
            roundNumber = 1;
            break;
    }
    
    // 更新轮次显示
    [self updateRoundDisplay:roundNumber];
    
    // 清空现有公共牌
    [self.communityCardsNode removeAllChildren];
    
    // 添加公共牌区域背景
    SKShapeNode *communityArea = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(280, 80) cornerRadius:8];
    communityArea.fillColor = [UIColor colorWithWhite:0.0 alpha:0.3];
    communityArea.strokeColor = [UIColor sp_chipGoldColor];
    communityArea.lineWidth = 2;
    communityArea.position = CGPointMake(0, 0);
    [self.communityCardsNode addChild:communityArea];
    
    // 公共牌标签
    SKLabelNode *communityLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial"];
    communityLabel.text = @"公共牌区域";
    communityLabel.fontSize = 14;
    communityLabel.fontColor = [UIColor sp_secondaryTextColor];
    communityLabel.position = CGPointMake(0, 50);
    [self.communityCardsNode addChild:communityLabel];
    
    // 显示公共牌
    for (NSInteger i = 0; i < cards.count; i++) {
        SPCard *card = cards[i];
        SKLabelNode *cardNode = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
        cardNode.text = [card description];
        cardNode.fontSize = 14;
        cardNode.fontColor = [UIColor whiteColor];
        cardNode.position = CGPointMake(-100 + i * 50, 0);
        cardNode.zPosition = 1;
        [self.communityCardsNode addChild:cardNode];
    }
}

- (void)updatePlayerDisplay:(SPPlayer *)player atPosition:(NSInteger)position {
    NSLog(@"GameScene: 更新玩家 %@ 在位置 %ld 的显示", player.name, (long)position);
    
    if (position >= self.playerNodes.count) return;
    
    SKNode *playerNode = self.playerNodes[position];
    
    // 根据玩家类型显示正确的名称 - 修复位置映射
    if ([player.name isEqualToString:@"玩家"]) {
        // 当前玩家不应该显示在AI位置，隐藏这个节点
        playerNode.hidden = YES;
        return;
    } else {
        // AI玩家显示在对应位置
        playerNode.hidden = NO;
    }
    
    // 更新名称标签
    SKLabelNode *nameLabel = (SKLabelNode *)[playerNode childNodeWithName:@"nameLabel"];
    if (nameLabel) {
        nameLabel.text = [NSString stringWithFormat:@"AI-%ld", (long)position + 1];
    }
    
    // 更新筹码标签
    SKLabelNode *chipsLabel = (SKLabelNode *)[playerNode childNodeWithName:@"chipsLabel"];
    if (chipsLabel) {
        chipsLabel.text = [NSString stringWithFormat:@"¥%ld", (long)player.chips];
    }
    
    // 更新状态标签
    SKLabelNode *statusLabel = (SKLabelNode *)[playerNode childNodeWithName:@"statusLabel"];
    if (statusLabel) {
        statusLabel.text = @"等待中";
    }
    
    // AI玩家不显示手牌数量
    SKLabelNode *cardsLabel = (SKLabelNode *)[playerNode childNodeWithName:@"cardsLabel"];
    if (cardsLabel) {
        [cardsLabel removeFromParent];
    }
}

- (void)updatePotDisplay:(NSInteger)amount {
    NSLog(@"GameScene: 更新底池显示 %ld", (long)amount);
    self.potLabel.text = [NSString stringWithFormat:@"底池: ¥%ld", (long)amount];
}

- (void)updateGameStateDisplay:(SPGameState)state {
    NSLog(@"GameScene: 更新游戏状态显示 %ld", (long)state);
    
    NSString *stateText;
    switch (state) {
        case SPGameStateIdle:
            stateText = @"等待开始";
            break;
        case SPGameStateDealing:
            stateText = @"发牌中";
            break;
        case SPGameStatePreFlop:
            stateText = @"翻牌前";
            break;
        case SPGameStateFlop:
            stateText = @"翻牌";
            break;
        case SPGameStateTurn:
            stateText = @"转牌";
            break;
        case SPGameStateRiver:
            stateText = @"河牌";
            break;
        case SPGameStateShowdown:
            stateText = @"摊牌";
            break;
        case SPGameStateEnded:
            stateText = @"游戏结束";
            break;
        default:
            stateText = @"未知状态";
            break;
    }
    
    self.gameStateLabel.text = stateText;
}

- (void)updateRoundDisplay:(NSInteger)round {
    NSLog(@"GameScene: 更新轮次显示 %ld", (long)round);
    
    NSString *roundText;
    switch (round) {
        case 1:
            roundText = @"第1轮";
            break;
        case 2:
            roundText = @"第2轮";
            break;
        case 3:
            roundText = @"第3轮";
            break;
        case 4:
            roundText = @"第4轮";
            break;
        case 5:
            roundText = @"第5轮";
            break;
        default:
            roundText = [NSString stringWithFormat:@"第%ld轮", (long)round];
            break;
    }
    
    self.roundLabel.text = roundText;
}

- (void)updateActionButtons {
    NSLog(@"GameScene: 更新操作按钮");
    // 保持原有按钮，不需要重新创建
}

- (void)handlePlayerAction:(SPPlayerAction)action amount:(NSInteger)amount {
    NSLog(@"GameScene: 处理玩家操作 %ld，金额 %ld", (long)action, (long)amount);
    
    // 根据操作类型调用GameManager的相应方法
    switch (action) {
        case SPPlayerActionFold:
            [self.gameManager playerFold];
            break;
        case SPPlayerActionCheck:
            [self.gameManager playerCheck];
            break;
        case SPPlayerActionCall:
            [self.gameManager playerCall];
            break;
        case SPPlayerActionRaise:
            [self.gameManager playerRaise:amount];
            break;
        case SPPlayerActionAllIn:
            [self.gameManager playerAllIn];
            break;
        default:
            break;
    }
}

#pragma mark - SPGameManagerDelegate

- (void)gameManager:(SPGameManager *)manager didChangeState:(SPGameState)newState {
    NSLog(@"GameScene: 游戏状态变化为 %ld", (long)newState);
    [self updateGameStateDisplay:newState];
}

- (void)gameManager:(SPGameManager *)manager 
         playerDidAct:(SPPlayer *)player 
               action:(SPPlayerAction)action 
               amount:(NSInteger)amount {
    NSLog(@"GameScene: 玩家 %@ 执行操作 %ld，金额 %ld", player.name, (long)action, (long)amount);
    
    // 更新玩家显示
    [self updatePlayerDisplay:player atPosition:player.position];
    
    // 更新底池显示
    [self updatePotDisplay:manager.currentPot];
}

- (void)gameManager:(SPGameManager *)manager 
         didDealCards:(NSArray<SPCard *> *)cards 
              toPlayer:(SPPlayer *)player {
    NSLog(@"GameScene: 发牌给玩家 %@", player.name);
    
    // 更新玩家显示
    [self updatePlayerDisplay:player atPosition:player.position];
}

- (void)gameManager:(SPGameManager *)manager 
    didUpdateCommunityCards:(NSArray<SPCard *> *)cards 
                      round:(SPGameState)round {
    NSLog(@"GameScene: 更新公共牌");
    [self updateCommunityCards:cards round:round];
}

- (void)gameManager:(SPGameManager *)manager 
           gameDidEnd:(SPPlayer * _Nullable)winner 
            winAmount:(NSInteger)winAmount 
          winningHand:(SPHandResult * _Nullable)winningHand {
    NSLog(@"GameScene: 游戏结束，获胜者 %@，获胜金额 %ld", winner.name, (long)winAmount);
    
    if (winner) {
        CGPoint winnerPosition = [self getPlayerPosition:winner.position];
        [self showWinnerAnimation:winnerPosition winAmount:winAmount];
    }
}

#pragma mark - 触摸处理

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];
    SKNode *touchedNode = [self nodeAtPoint:location];
    
    NSLog(@"GameScene: 触摸位置 %@，触摸节点 %@，节点类型 %@", NSStringFromCGPoint(location), touchedNode.name, NSStringFromClass([touchedNode class]));
    
    // 如果直接触摸的节点没有名称，尝试查找父节点
    if (!touchedNode.name) {
        // 检查是否是按钮的子节点（如标签）
        SKNode *parent = touchedNode.parent;
        while (parent && !parent.name) {
            parent = parent.parent;
        }
        if (parent && parent.name) {
            touchedNode = parent;
            NSLog(@"GameScene: 找到父节点 %@", touchedNode.name);
        }
    }
    
    // 处理按钮点击
    if ([touchedNode.name isEqualToString:@"startButton"]) {
        NSLog(@"GameScene: 检测到开始游戏按钮点击");
        [self handleStartGameButton];
    } else if ([touchedNode.name isEqualToString:@"foldButton"]) {
        NSLog(@"GameScene: 检测到弃牌按钮点击");
        [self handlePlayerActionButton:SPPlayerActionFold amount:0];
    } else if ([touchedNode.name isEqualToString:@"callButton"]) {
        NSLog(@"GameScene: 检测到跟注按钮点击");
        [self handlePlayerActionButton:SPPlayerActionCall amount:200];
    } else if ([touchedNode.name isEqualToString:@"raiseButton"]) {
        NSLog(@"GameScene: 检测到加注按钮点击");
        [self handlePlayerActionButton:SPPlayerActionRaise amount:400];
    } else if ([touchedNode.name isEqualToString:@"closeResultButton"]) {
        NSLog(@"GameScene: 检测到关闭结果按钮点击");
        [self closeGameResultPopup];
    } else {
        NSLog(@"GameScene: 未识别的按钮点击，节点名称: %@", touchedNode.name);
    }
}

- (void)handleStartGameButton {
    NSLog(@"GameScene: 开始游戏按钮被点击");
    
    // 创建游戏ViewModel（只在第一次点击时创建）
    if (!self.gameViewModel) {
        self.gameViewModel = [[SPGameViewModel alloc] init];
        [self bindGameViewModel];
    }
    
    // 开始新游戏
    NSArray<NSString *> *playerNames = @[@"玩家", @"AI-1", @"AI-2", @"AI-3", @"AI-4"];
    [self.gameViewModel startNewGameWithPlayers:playerNames aiDifficulty:SPAIDifficultyMedium];
    
    // 隐藏开始游戏按钮
    SKNode *startButton = [self.actionButtonsNode childNodeWithName:@"startButton"];
    if (startButton) {
        startButton.hidden = YES;
    }
    
    // 更新游戏状态显示
    [self updateGameStateDisplay:SPGameStatePreFlop];
    
    // 初始化轮次显示
    [self updateRoundDisplay:1];
    
    NSLog(@"GameScene: 游戏已开始，等待玩家操作");
}

- (void)bindGameViewModel {
    __weak typeof(self) weakSelf = self;
    
    // 游戏状态变化
    self.gameViewModel.gameStateDidChange = ^(SPGameState newState) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf updateGameStateDisplay:newState];
        });
    };
    
    // 底池变化
    self.gameViewModel.potDidChange = ^(NSInteger newPot) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf updatePotDisplay:newPot];
        });
    };
    
    // 公共牌更新
    self.gameViewModel.communityCardsDidUpdate = ^(NSArray<SPCard *> *cards) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf updateCommunityCards:cards round:weakSelf.gameViewModel.gameState];
        });
    };
    
    // 玩家手牌更新
    self.gameViewModel.playerCardsDidUpdate = ^(NSArray<SPCard *> *cards) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf showPlayerCards:cards];
        });
    };
    
    // 玩家行动
    self.gameViewModel.playerDidAct = ^(SPPlayer *player, SPPlayerAction action, NSInteger amount) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf handlePlayerAction:player action:action amount:amount];
        });
    };
    
    // 游戏结束
    self.gameViewModel.gameDidEnd = ^(SPPlayer *winner, NSInteger winAmount) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf handleGameEnd:winner winAmount:winAmount];
        });
    };
}

- (void)showPlayerCards:(NSArray<SPCard *> *)cards {
    NSLog(@"GameScene: 显示玩家手牌 %@", cards);
    
    // 在玩家区域显示手牌
    CGPoint playerPosition = CGPointMake(self.size.width / 2, 160);
    
    // 移除旧的手牌显示
    for (SKNode *child in self.children) {
        if ([child.name hasPrefix:@"playerCard_"]) {
            [child removeFromParent];
        }
    }
    
    // 显示新手牌
    for (NSInteger i = 0; i < cards.count; i++) {
        SPCard *card = cards[i];
        
        SKLabelNode *cardNode = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
        cardNode.text = [card description];
        cardNode.fontSize = 16;
        cardNode.fontColor = [UIColor whiteColor];
        cardNode.position = CGPointMake(playerPosition.x - 30 + i * 60, playerPosition.y);
        cardNode.zPosition = 10;
        cardNode.name = [NSString stringWithFormat:@"playerCard_%ld", (long)i];
        
        [self addChild:cardNode];
    }
}

- (void)handlePlayerActionButton:(SPPlayerAction)action amount:(NSInteger)amount {
    NSLog(@"GameScene: 玩家点击操作按钮 %ld，金额 %ld", (long)action, (long)amount);
    
    // 检查游戏是否已经开始
    if (!self.gameViewModel || self.gameViewModel.gameState == SPGameStateIdle) {
        NSLog(@"GameScene: 游戏尚未开始，无法执行操作");
        return;
    }
    
    // 检查是否是玩家的回合
    if (self.gameViewModel.activePlayer != self.gameViewModel.currentPlayer) {
        NSLog(@"GameScene: 不是玩家的回合，无法执行操作");
        return;
    }
    
    // 根据操作类型调用ViewModel的相应方法
    switch (action) {
        case SPPlayerActionFold:
            [self.gameViewModel playerFold];
            break;
        case SPPlayerActionCall:
            [self.gameViewModel playerCall];
            break;
        case SPPlayerActionRaise:
            [self.gameViewModel playerRaise:amount];
            break;
        case SPPlayerActionCheck:
            [self.gameViewModel playerCheck];
            break;
        case SPPlayerActionAllIn:
            [self.gameViewModel playerAllIn];
            break;
    }
    
    // 显示操作动画
    [self showActionAnimation:action amount:amount atPosition:[self getPlayerPosition:0]]; // 0是玩家位置
}

- (void)handlePlayerAction:(SPPlayer *)player action:(SPPlayerAction)action amount:(NSInteger)amount {
    NSLog(@"GameScene: 玩家 %@ 执行操作 %ld，金额 %ld", player.name, (long)action, (long)amount);
    
    // 更新玩家显示
    [self updatePlayerDisplay:player atPosition:player.position];
    
    // 更新底池显示
    [self updatePotDisplay:self.gameViewModel.currentPot];
    
    // 显示操作动画
    [self showActionAnimation:action amount:amount atPosition:[self getPlayerPosition:player.position]];
}

- (void)showActionAnimation:(SPPlayerAction)action amount:(NSInteger)amount atPosition:(CGPoint)position {
    NSString *actionText;
    UIColor *actionColor;
    
    switch (action) {
        case SPPlayerActionFold:
            actionText = @"弃牌";
            actionColor = [UIColor redColor];
            break;
        case SPPlayerActionCheck:
            actionText = @"过牌";
            actionColor = [UIColor yellowColor];
            break;
        case SPPlayerActionCall:
            actionText = [NSString stringWithFormat:@"跟注 ¥%ld", (long)amount];
            actionColor = [UIColor greenColor];
            break;
        case SPPlayerActionRaise:
            actionText = [NSString stringWithFormat:@"加注 ¥%ld", (long)amount];
            actionColor = [UIColor blueColor];
            break;
        case SPPlayerActionAllIn:
            actionText = @"全下";
            actionColor = [UIColor orangeColor];
            break;
    }
    
    SKLabelNode *actionLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    actionLabel.text = actionText;
    actionLabel.fontSize = 18;
    actionLabel.fontColor = actionColor;
    actionLabel.position = CGPointMake(position.x, position.y + 50);
    actionLabel.zPosition = 15;
    [self addChild:actionLabel];
    
    // 淡出动画
    SKAction *fadeOut = [SKAction fadeAlphaTo:0 duration:1.0];
    SKAction *moveUp = [SKAction moveByX:0 y:20 duration:1.0];
    SKAction *group = [SKAction group:@[fadeOut, moveUp]];
    
    [actionLabel runAction:group completion:^{
        [actionLabel removeFromParent];
    }];
}

- (void)handleGameEnd:(SPPlayer *)winner winAmount:(NSInteger)winAmount {
    NSLog(@"GameScene: 游戏结束，获胜者 %@，获胜金额 %ld", winner.name, (long)winAmount);
    
    if (winner) {
        CGPoint winnerPosition = [self getPlayerPosition:winner.position];
        [self showWinnerAnimation:winnerPosition winAmount:winAmount];
    }
    
    // 显示游戏结果弹出框
    SPHandResult *winningHand = [[SPHandResult alloc] init];
    winningHand.handRank = SPHandRankHighCard; // 暂时设置为高牌，实际应该从游戏逻辑中获取
    
    [self showGameResultPopup:winner 
                   allPlayers:self.gameViewModel.players 
                   winningHand:winningHand];
    
    // 显示重新开始按钮
    [self showRestartButton];
}

- (void)showRestartButton {
    SKShapeNode *restartButton = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(120, 40) cornerRadius:6];
    restartButton.position = CGPointMake(self.size.width / 2, 60);
    restartButton.fillColor = [UIColor colorWithRed:0.2 green:0.6 blue:0.2 alpha:0.9];
    restartButton.strokeColor = [UIColor colorWithRed:0.1 green:0.4 blue:0.1 alpha:1.0];
    restartButton.lineWidth = 2;
    restartButton.name = @"restartButton";
    restartButton.zPosition = 20;
    [self addChild:restartButton];
    
    SKLabelNode *restartLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    restartLabel.text = @"重新开始";
    restartLabel.fontSize = 14;
    restartLabel.fontColor = [UIColor whiteColor];
    restartLabel.position = CGPointMake(0, 0);
    restartLabel.zPosition = 21;
    [restartButton addChild:restartLabel];
}

#pragma mark - 辅助方法

- (CGPoint)getPlayerPosition:(NSInteger)index {
    // 根据玩家索引返回位置
    CGFloat centerX = self.size.width / 2;
    CGFloat centerY = self.size.height / 2;
    
    switch (index) {
        case 0: // 当前玩家（底部）
            return CGPointMake(centerX, 200);
        case 1: // 左上 AI-1
            return CGPointMake(centerX - 140, centerY + 80);
        case 2: // 右上 AI-2
            return CGPointMake(centerX + 140, centerY + 80);
        case 3: // 左下 AI-3
            return CGPointMake(centerX - 140, centerY - 80);
        case 4: // 右下 AI-4
            return CGPointMake(centerX + 140, centerY - 80);
        default:
            return CGPointMake(centerX, centerY);
    }
}

- (void)showGameResultPopup:(SPPlayer *)winner 
                  allPlayers:(NSArray<SPPlayer *> *)players 
                  winningHand:(SPHandResult *)winningHand {
    NSLog(@"GameScene: 显示游戏结果弹出框");
    
    // 创建半透明背景
    SKShapeNode *background = [SKShapeNode shapeNodeWithRectOfSize:self.size];
    background.position = CGPointMake(self.size.width / 2, self.size.height / 2);
    background.fillColor = [UIColor colorWithWhite:0.0 alpha:0.7];
    background.strokeColor = [UIColor clearColor];
    background.zPosition = 100;
    background.name = @"resultBackground";
    [self addChild:background];
    
    // 创建弹出框
    CGSize popupSize = CGSizeMake(300, 400);
    SKShapeNode *popup = [SKShapeNode shapeNodeWithRectOfSize:popupSize cornerRadius:12];
    popup.position = CGPointMake(self.size.width / 2, self.size.height / 2);
    popup.fillColor = [UIColor colorWithWhite:0.1 alpha:0.95];
    popup.strokeColor = [UIColor sp_chipGoldColor];
    popup.lineWidth = 3;
    popup.zPosition = 101;
    popup.name = @"resultPopup";
    [self addChild:popup];
    
    // 标题
    SKLabelNode *titleLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    titleLabel.text = @"游戏结果";
    titleLabel.fontSize = 20;
    titleLabel.fontColor = [UIColor sp_chipGoldColor];
    titleLabel.position = CGPointMake(0, popupSize.height / 2 - 30);
    titleLabel.zPosition = 102;
    [popup addChild:titleLabel];
    
    // 赢家信息
    SKLabelNode *winnerLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    winnerLabel.text = [NSString stringWithFormat:@"🏆 获胜者: %@", winner.name];
    winnerLabel.fontSize = 16;
    winnerLabel.fontColor = [UIColor sp_chipGoldColor];
    winnerLabel.position = CGPointMake(0, popupSize.height / 2 - 70);
    winnerLabel.zPosition = 102;
    [popup addChild:winnerLabel];
    
    // 获胜牌型
    SKLabelNode *handTypeLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    handTypeLabel.text = [NSString stringWithFormat:@"牌型: %@", [self getHandTypeDescription:winningHand.handRank]];
    handTypeLabel.fontSize = 14;
    handTypeLabel.fontColor = [UIColor whiteColor];
    handTypeLabel.position = CGPointMake(0, popupSize.height / 2 - 100);
    handTypeLabel.zPosition = 102;
    [popup addChild:handTypeLabel];
    
    // 分隔线
    SKShapeNode *separator = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(popupSize.width - 40, 1)];
    separator.position = CGPointMake(0, popupSize.height / 2 - 130);
    separator.fillColor = [UIColor sp_chipGoldColor];
    separator.strokeColor = [UIColor sp_chipGoldColor];
    separator.zPosition = 102;
    [popup addChild:separator];
    
    // 所有玩家牌型信息
    CGFloat startY = popupSize.height / 2 - 160;
    CGFloat lineHeight = 25;
    
    for (NSInteger i = 0; i < players.count; i++) {
        SPPlayer *player = players[i];
        CGFloat yPos = startY - i * lineHeight;
        
        // 玩家名称
        SKLabelNode *playerNameLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial"];
        playerNameLabel.text = [NSString stringWithFormat:@"%@:", player.name];
        playerNameLabel.fontSize = 12;
        playerNameLabel.fontColor = [player.name isEqualToString:winner.name] ? [UIColor sp_chipGoldColor] : [UIColor whiteColor];
        playerNameLabel.position = CGPointMake(-popupSize.width / 2 + 20, yPos);
        playerNameLabel.zPosition = 102;
        playerNameLabel.horizontalAlignmentMode = SKLabelHorizontalAlignmentModeLeft;
        [popup addChild:playerNameLabel];
        
        // 玩家牌型
        NSString *handType = [self getPlayerHandTypeDescription:player];
        SKLabelNode *playerHandLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial"];
        playerHandLabel.text = handType;
        playerHandLabel.fontSize = 12;
        playerHandLabel.fontColor = [player.name isEqualToString:winner.name] ? [UIColor sp_chipGoldColor] : [UIColor lightGrayColor];
        playerHandLabel.position = CGPointMake(0, yPos);
        playerHandLabel.zPosition = 102;
        [popup addChild:playerHandLabel];
    }
    
    // 关闭按钮
    SKShapeNode *closeButton = [SKShapeNode shapeNodeWithRectOfSize:CGSizeMake(100, 40) cornerRadius:6];
    closeButton.position = CGPointMake(0, -popupSize.height / 2 + 30);
    closeButton.fillColor = [UIColor colorWithRed:0.2 green:0.6 blue:0.2 alpha:0.9];
    closeButton.strokeColor = [UIColor colorWithRed:0.1 green:0.4 blue:0.1 alpha:1.0];
    closeButton.lineWidth = 2;
    closeButton.zPosition = 102;
    closeButton.name = @"closeResultButton";
    [popup addChild:closeButton];
    
    SKLabelNode *closeLabel = [SKLabelNode labelNodeWithFontNamed:@"Arial-BoldMT"];
    closeLabel.text = @"确定";
    closeLabel.fontSize = 14;
    closeLabel.fontColor = [UIColor whiteColor];
    closeLabel.position = CGPointMake(0, 0);
    closeLabel.zPosition = 103;
    [closeButton addChild:closeLabel];
    
    // 添加淡入动画
    popup.alpha = 0;
    SKAction *fadeIn = [SKAction fadeAlphaTo:1.0 duration:0.3];
    [popup runAction:fadeIn];
}

- (NSString *)getHandTypeDescription:(SPHandRank)handRank {
    switch (handRank) {
        case SPHandRankHighCard:
            return @"高牌";
        case SPHandRankOnePair:
            return @"一对";
        case SPHandRankTwoPair:
            return @"两对";
        case SPHandRankThreeOfAKind:
            return @"三条";
        case SPHandRankStraight:
            return @"顺子";
        case SPHandRankFlush:
            return @"同花";
        case SPHandRankFullHouse:
            return @"葫芦";
        case SPHandRankFourOfAKind:
            return @"四条";
        case SPHandRankStraightFlush:
            return @"同花顺";
        case SPHandRankRoyalFlush:
            return @"皇家同花顺";
        default:
            return @"未知牌型";
    }
}

- (NSString *)getPlayerHandTypeDescription:(SPPlayer *)player {
    // 这里应该根据玩家的实际牌型返回描述
    // 暂时返回一个简单的描述，实际应该根据玩家的手牌和公共牌计算
    if (player.hasFolded) {
        return @"已弃牌";
    }
    
    // 这里应该调用牌型判断逻辑
    // 暂时返回一个占位符
    return @"高牌";
}

- (void)closeGameResultPopup {
    NSLog(@"GameScene: 关闭游戏结果弹出框");
    
    // 移除弹出框和背景
    SKNode *resultPopup = [self childNodeWithName:@"resultPopup"];
    SKNode *resultBackground = [self childNodeWithName:@"resultBackground"];
    
    if (resultPopup) {
        [resultPopup removeFromParent];
    }
    if (resultBackground) {
        [resultBackground removeFromParent];
    }
}

@end